using System;
using System.Collections.Generic;
using System.Text;

using HandyIRCCore;

namespace HandyIRCChat
{
    public class ChannelObject
    {
        public ChannelObject(HandyLogic hl, Core c, string ch)
        {
            handyLogic = hl;
            ircCore = c;
            channel = ch;

            handyLogic.ChannelMessageEvent += 
                new HandyLogic.ChannelMessageEventHandler(handyLogic_ChannelMessageEvent);
        }

        #region Declarations

        private const int bufferMaxLength = 4096;

        // Length cannot be greater than bufferMaxLength
        private string messageBuffer = "";

        private HandyLogic handyLogic;

        private Core ircCore;

        private string channel;

        private ChannelForm channelForm = null;

        public event ChannelMessageEventHandler ChannelMessageEvent;

        public delegate void ChannelMessageEventHandler(object sender,
                                                        string message);

        #endregion

        #region Properties

        public string MessageBuffer
        {
            get
            {
                return messageBuffer;
            }
        }

        public string Channel
        {
            get
            {
                return channel;
            }
        }

        public ChannelForm ChannelForm
        {
            get
            {
                return channelForm;
            }

            set
            {
                channelForm = value;
            }
        }

        #endregion

        #region Methods

        public void SendMessage(string s)
        {
            if (handyLogic.IsConnected)
            {
                ircCore.SendMessage("PRIVMSG " + channel + " " + s);

                string message = "<" + ircCore.UserNick + "> " + s + Environment.NewLine;
                AppendToMessageBuffer(message);

                if (ChannelMessageEvent != null)
                    ChannelMessageEvent(this, message);
            }
        }

        private void handyLogic_ChannelMessageEvent(object sender, HandyIRCMessage msg)
        {
            if (msg.Parameters[0] == channel)
            {
                string message = "<" + msg.Nick + "> " + msg.Parameters[1] + Environment.NewLine;
                AppendToMessageBuffer(message);

                if (ChannelMessageEvent != null)
                    ChannelMessageEvent(this, message);
            }
        }

        private void AppendToMessageBuffer(string message)
        {
            StringBuilder sb = new StringBuilder(messageBuffer);

            sb.Append(message);
            if (sb.Length > bufferMaxLength)
                sb.Remove(0, sb.Length - bufferMaxLength);

            messageBuffer = sb.ToString();
        }

        #endregion
    }
}
